package com.changgou.file.controller;
import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.file.util.FastDFSClient;
import com.changgou.file.util.FastDFSFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 *
 */
@RestController
@RequestMapping("/file")
public class FileController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @PostMapping("/upload")
    public Result upload(@PathVariable("file") MultipartFile file) {
        String fileName = null;
        try {
            //获取文件全名
            fileName = file.getOriginalFilename();
            //获取文件内容
            byte[] fileContenxt = file.getBytes();
            //获取文件扩展名
            String extName = fileName.substring(fileName.lastIndexOf("."));
            //构造一个FastDFSFile对象
            FastDFSFile fastDFSFile = new FastDFSFile(fileName, fileContenxt, extName);

            String[] uploadResult = FastDFSClient.upload(fastDFSFile);

            if (null != uploadResult && uploadResult.length == 2) {
                String groupName = uploadResult[0];//获取文件名
                String remoteFilePath = uploadResult[1];//获取文件在储存服务器的远程储存路径
                //TODP 将路径储存到数据库表中

                String url = FastDFSClient.getTrackerUrl() + groupName + "/" + remoteFilePath;
                logger.info("上传成功,url:{}", url);
                return new Result(true, StatusCode.OK, "上传成功", url);
            } else {
                logger.info("上传失败,fileName:{}", fileName);
                return new Result(false, StatusCode.ERROR, "上传失败");
            }

        } catch (IOException e) {
            e.printStackTrace();
            logger.info("上传失败,fileName:{}", fileName);
            return new Result(false, StatusCode.ERROR, "上传失败");
        }
    }
}
